package krao.parser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import krao.test.FileParserTest;

import org.apache.log4j.Logger;

import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;

/**
 * Class responsible for parsing input data into Jena OntModel.
 * 
 * @author Pepe
 */
public class ModelParser {
	private final static Logger logger = Logger.getLogger(FileParserTest.class);
	private static final FileFormat DEFAULT_FORMAT = FileFormat.TTL;

	/**
	 * Loads the appropriate model from serialized RDF represented as a stream.
	 * 
	 * @param inputStream
	 *            Input stream
	 * @param fileFormat
	 *            RDF serialization format of the stream.
	 * @return
	 * @return the model
	 */
	public static OntModel readFromStream(final InputStream inputStream,
			final FileFormat format) {
		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);// OWL_LITE_MEM);
		return (OntModel) model.read(inputStream, null, "TTL");
	}

	/**
	 * Wrapper for {@link #readFromStream(InputStream, FileFormat)}
	 * 
	 * @throws FileNotFoundException
	 */
	public static OntModel readFromFile(final String fileName, final FileFormat format)
			throws FileNotFoundException {
		FileInputStream inputStream;
		try {
			inputStream = new FileInputStream(fileName);
			return readFromStream(inputStream, format);
		} catch (FileNotFoundException e) {
			logger.error("File " + fileName + " was not found.\n" + e);
			throw e;
		}
	}

	/**
	 * Wrapper for {@link #readFromStream(InputStream, FileFormat)}
	 */
	public static OntModel readFromFile(final String fileName)
			throws FileNotFoundException {
		return readFromFile(fileName, DEFAULT_FORMAT);
	}

	/**
	 * Wrapper for {@link #readFromStream(InputStream, FileFormat)}
	 */
	public static OntModel readFromStream(final InputStream inputStream) {
		return readFromStream(inputStream, DEFAULT_FORMAT);
	}
}
